package org.example;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelParser {
    public static <T> List<T> parseExcelToEntities(String filePath, Class<T> entityType) {
        List<T> entities = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(filePath)) {
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 假设解析第一个Sheet
            // 获取实体类型的所有字段
            Field[] fields = entityType.getDeclaredFields();
            // 创建列索引映射，将中文释义与列索引对应起来
            Map<String, Integer> columnIndexMap = createColumnIndexMap(sheet, fields);
            // 遍历每一行（跳过标题行）
            for (int rowIdx = 1; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
                Row row = sheet.getRow(rowIdx);
                if (row != null) {
                    // 创建实体对象
                    T entity = entityType.getDeclaredConstructor().newInstance();
                    // 遍历实体类型的字段
                    for (Field field : fields) {
                        // 获取字段的中文释义
                        String columnName = field.getName();
                        if (field.isAnnotationPresent(ChineseName.class)) {
                            ChineseName chineseNameAnnotation = field.getAnnotation(ChineseName.class);
                            columnName = chineseNameAnnotation.value();
                        }
                        // 获取对应的列索引
                        int columnIndex = columnIndexMap.get(columnName);
                        // 解析对应列的数据，并设置到实体对象的属性上
                        Cell cell = row.getCell(columnIndex);
                        if (cell != null) {
                            setEntityFieldValue(entity, field, cell);
                        }
                    }
                    // 将实体对象添加到列表中
                    entities.add(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entities;
    }

    private static Map<String, Integer> createColumnIndexMap(Sheet sheet, Field[] fields) {
        Map<String, Integer> columnIndexMap = new HashMap<>();
        Row headerRow = sheet.getRow(0);
        for (Cell cell : headerRow) {
            String columnName = cell.getStringCellValue();
            for (Field field : fields) {
                if (field.isAnnotationPresent(ChineseName.class)) {
                    ChineseName chineseNameAnnotation = field.getAnnotation(ChineseName.class);
                    if (columnName.equals(chineseNameAnnotation.value())) {
                        columnIndexMap.put(columnName, cell.getColumnIndex());
                        break;
                    }
                }
            }
        }

        return columnIndexMap;
    }

    private static <T> void setEntityFieldValue(T entity, Field field, Cell cell) throws IllegalAccessException {
        field.setAccessible(true);
        if (field.getType() == String.class) {
            field.set(entity, cell.getStringCellValue());
        } else if (field.getType() == int.class || field.getType() == Integer.class) {
            field.set(entity, (int) cell.getNumericCellValue());
        } else if (field.getType() == double.class || field.getType() == Double.class) {
            field.set(entity, cell.getNumericCellValue());
        } else if (field.getType() == boolean.class || field.getType() == Boolean.class) {
            field.set(entity, cell.getBooleanCellValue());
        }
    }

    public static void main(String[] args) {
        String filePath = "testExcel/花名册.xls";
        List<student> entities = parseExcelToEntities(filePath, student.class);
        // 打印解析后的实体对象
        for (student entity : entities) {
           log.info(String.valueOf(entity));
        }
   }
}